#include "ImageDownloader.h"
#include "ui_imagedownloader.h"
#include "ImageDownloader.h"
ImageDownloader::ImageDownloader(const QString &parameter,QWidget *parent)
    : QDialog(parent)
    , m_networkManager(new QNetworkAccessManager(this))
    , m_currentLabel(nullptr)
    , m_qiniuUrl("http://svxxs5ooh.hn-bkt.clouddn.com/")
    , img(new Ui::ImageDownloader)
{
    m_qiniuUrl.append(parameter);
    img->setupUi(this);
    downloadImage(m_qiniuUrl,img->label);
}

ImageDownloader::~ImageDownloader()
{

}
void ImageDownloader::downloadQiniuImage(QLabel *targetLabel)
{
    downloadImage(m_qiniuUrl, targetLabel);
}

void ImageDownloader::downloadImage(const QString &url, QLabel *targetLabel)
{
    if (!targetLabel)
        return;

    m_currentLabel = targetLabel;
    m_currentLabel->setText("下载中...");

    // 创建网络请求
    QNetworkRequest request(url);

    // 设置请求头，有助于七牛云CDN处理
    request.setRawHeader("User-Agent", "Mozilla/5.0 (Qt Application)");

    // 设置不使用缓存，确保获取最新版本
    request.setAttribute(QNetworkRequest::CacheLoadControlAttribute,
                         QNetworkRequest::AlwaysNetwork);

    // Qt 5.9+支持的重定向策略
    #if QT_VERSION >= QT_VERSION_CHECK(5, 9, 0)
    request.setAttribute(QNetworkRequest::RedirectPolicyAttribute,
                         QNetworkRequest::NoLessSafeRedirectPolicy);
    #endif

    // 发送网络请求
    QNetworkReply *reply = m_networkManager->get(request);

    // 连接信号和槽
    connect(reply, &QNetworkReply::finished, this, &ImageDownloader::onImageDownloaded);
    connect(reply, &QNetworkReply::downloadProgress, this, &ImageDownloader::onDownloadProgress);

    qDebug() << "开始下载图片:" << url;
}


void ImageDownloader::onImageDownloaded()
{
    // 获取发送信号的网络回复
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
    if (!reply || !m_currentLabel) {
        if (reply) reply->deleteLater();
        return;
    }

    // 处理可能的错误
    if (reply->error() != QNetworkReply::NoError) {
        m_currentLabel->setText("下载失败: " + reply->errorString());
        qDebug() << "图片下载失败:" << reply->errorString();
        reply->deleteLater();
        return;
    }

    // 读取图片数据
    QByteArray imageData = reply->readAll();
    QPixmap pixmap;

    // 尝试加载图片数据
    if (pixmap.loadFromData(imageData)) {
        // 根据标签大小缩放图片，保持宽高比

        img->label->setPixmap(pixmap);

        // 重要：调整标签大小为图片实际大小
        img->label->setMinimumSize(pixmap.size());
        img->label->setMaximumSize(pixmap.size());

        // 调整窗口大小以适应图片
        adjustSize();

        qDebug() << "图片尺寸:" << pixmap.width() << "x" << pixmap.height();
//        m_currentLabel->setPixmap(pixmap.scaled(
//            m_currentLabel->size(),
//            Qt::KeepAspectRatio,
//            Qt::SmoothTransformation
//        ));
//        qDebug() << "图片下载成功 - 大小:" << pixmap.width() << "x" << pixmap.height();

//        // 可选：保存图片到文件
//        // pixmap.save("downloaded_image.png");
    } else {
        m_currentLabel->setText("无法解析图片数据");
        qDebug() << "无法解析图片数据";
    }

    // 清理资源
    reply->deleteLater();
}

void ImageDownloader::onDownloadProgress(qint64 bytesReceived, qint64 bytesTotal)
{
    if (m_currentLabel && bytesTotal > 0) {
        int percent = static_cast<int>((bytesReceived * 100) / bytesTotal);
        m_currentLabel->setText(QString("下载中... %1%").arg(percent));
    }
}

void downloadImage(const QString &url, const QString &saveFilePath)
{
    // 创建网络访问管理器
    QNetworkAccessManager *manager = new QNetworkAccessManager();

    // 创建网络请求
    QNetworkRequest request(url);
    request.setRawHeader("User-Agent", "Mozilla/5.0 (Qt Application)");

    // 发送GET请求
    QNetworkReply *reply = manager->get(request);

    // 处理下载完成事件
    QObject::connect(reply, &QNetworkReply::finished, [=]() {
        if (reply->error() == QNetworkReply::NoError) {
            // 读取所有下载数据
            QByteArray imageData = reply->readAll();

            // 方法2: 转换为QPixmap (如果需要显示)
            QPixmap pixmap;
            if (pixmap.loadFromData(imageData)) {
                qDebug() << "图片加载成功, 尺寸:" << pixmap.width() << "x" << pixmap.height();
                // 这里可以设置到QLabel或其他控件显示
                // imageLabel->setPixmap(pixmap);
            } else {
                qDebug() << "无法加载图片数据";
            }
        } else {
            qDebug() << "下载失败:" << reply->errorString();
        }

        // 清理资源
        reply->deleteLater();
        manager->deleteLater();
    });

    // 可选: 监听下载进度
    QObject::connect(reply, &QNetworkReply::downloadProgress, [](qint64 received, qint64 total) {
        if (total > 0) {
            qDebug() << "下载进度:" << (received * 100 / total) << "%";
        }
    });
}


